package com.mmm.user.service.impl;

import com.alibaba.fastjson.JSON;
import com.mmm.common.utils.EsPage;
import com.mmm.user.dao.DeliveryDao;
import com.mmm.user.entity.Delivery;
import com.mmm.user.variable.UniversityVariable;
import com.mmm.common.vo.Paging;
import com.mmm.user.entity.University;
import com.mmm.user.dao.UniversityDao;
import com.mmm.user.service.UniversityService;
import com.mmm.user.vo.UniversityPureVo;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.get.GetRequest;
import org.elasticsearch.action.get.GetResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.action.update.UpdateRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * (University)表服务实现类
 *
 * @author One
 * @since 2022-02-25 15:49:33
 */
@Service("universityService")
public class UniversityServiceImpl implements UniversityService {

    @Resource
    private UniversityDao universityDao;

    @Autowired
    private DeliveryDao deliveryDao;

    @Autowired
    private RestHighLevelClient client;

    /**
     * 通过ID查询单条数据
     *
     * @param id 主键
     * @return 实例对象
     */
    @Override
    public University queryById(Long id) {
        return this.universityDao.queryById(id);
    }

    /**
     * 查询多条数据
     *
     * @param offset 查询起始位置
     * @param limit  查询条数
     * @return 对象列表
     */
    @Override
    public List<University> queryAllByLimit(int offset, int limit) {
        return this.universityDao.queryAllByLimit(offset, limit);
    }

    /**
     * 新增数据
     *
     * @param university 实例对象
     * @return 实例对象
     */
    @Override
    @Transactional
    public University insert(University university) {
        Date date = new Date();
        university.setCreateTime(date);
        university.setUpdateTime(date);
        int i = this.universityDao.insert(university);
        if (i != 1) {
            throw new RuntimeException("university 数据插入失败");
        }
        try {
            IndexRequest request = new IndexRequest(UniversityVariable.UNIVERSITY).id(university.getId().toString());
            request.source(JSON.toJSONString(university), XContentType.JSON);
            client.index(request, RequestOptions.DEFAULT);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return university;
    }

    /**
     * 修改数据
     *
     * @param university 实例对象
     * @return 实例对象
     */
    @Override
    public University update(University university) {
        this.universityDao.update(university);
        try {
            UpdateRequest request = new UpdateRequest(UniversityVariable.UNIVERSITY, university.getId().toString());
            request.doc(
                    "university", university.getUniversity()
            );
            client.update(request, RequestOptions.DEFAULT);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return this.queryById(university.getId());
    }

    /**
     * 通过主键删除数据
     *
     * @param id 主键
     * @return 是否成功
     */
    @Override
    public boolean deleteById(Long id) {
        University university = this.queryById(id);
        university.setDeleteTime(new Date());
        int update = this.universityDao.update(university);
        if (update != 1) {
            throw new RuntimeException("university 删除失败，id=" + id);
        }
        try {
            DeleteRequest request = new DeleteRequest(UniversityVariable.UNIVERSITY).id(id.toString());
            client.delete(request, RequestOptions.DEFAULT);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return true;
    }

    @Override
    public University esById(Long id) {
        try {
            GetRequest request = new GetRequest(UniversityVariable.UNIVERSITY, id.toString());
            GetResponse response = this.client.get(request, RequestOptions.DEFAULT);
            String source = response.getSourceAsString();
            return JSON.parseObject(source, University.class);
        } catch (IOException e) {
            e.printStackTrace();
            throw new RuntimeException("university 根据 id 查询错误");
        }

    }

    @Override
    public Paging<UniversityPureVo> list(Integer page, Integer size) {
        try {
            SearchRequest request = new SearchRequest(UniversityVariable.UNIVERSITY);
            BoolQueryBuilder bool = QueryBuilders.boolQuery();
            request.source().query(bool)
                    .size(size)
                    .from(page)
                    .sort("createTime", SortOrder.ASC);
            SearchResponse search = client.search(request, RequestOptions.DEFAULT);

//            解析VO.class
            List<UniversityPureVo> vo=new ArrayList<>();
            for (SearchHit hit : search.getHits().getHits()) {
                String source = hit.getSourceAsString();
                UniversityPureVo universityPureVo = JSON.parseObject(source, UniversityPureVo.class);
                List<Delivery> all = deliveryDao.getAll(universityPureVo.getId());
                universityPureVo.setItems(all);
                vo.add(universityPureVo);
            }

            return EsPage.multilevelPage(vo,search,page,size);


        } catch (IOException e) {
            e.printStackTrace();
            throw new RuntimeException("university 分页 搜索失败");
        }
    }
}